package userGUI;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBAccess {
    private static final String DB_URL = "jdbc:mysql://localhost:3306/cargo?serverTimezone=UTC&characterEncoding=utf8"; // 替换为你实际的数据库名称
    private static final String DB_USER = "root"; // 替换为你实际的数据库用户名
    private static final String DB_PASSWORD = "asd081623A"; // 替换为你实际的数据库密码

    private static Connection connection;

    public static Connection getConnection(){
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    // 执行插入、更新和删除操作的方法
    public int executeUpdate(String sql) {
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            return statement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    // 执行删除操作并返回删除的记录数
    public int executeDelete(String sql) {
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            int rowsDeleted = statement.executeUpdate();
            return rowsDeleted;
        } catch (SQLException e) {
            e.printStackTrace();
            return -1;
        }
    }

    // 执行查询操作并返回ResultSet的方法
    public ResultSet executeQuery(String sql) {
        try {
            PreparedStatement statement = connection.prepareStatement(sql);
            return statement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
            return null;
        }
    }

    // 关闭数据库连接的方法
    public void closeConnection() {
        try {
            if (connection != null) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
